<template>
  <div class="global-search">
    <!-- 搜索触发器 -->
    <div class="search-trigger" @click="openSearch">
      <i class="fas fa-search search-icon"></i>
      <div class="search-placeholder">搜索功能、应用、文档...</div>
    </div>
    
    <!-- 搜索弹窗 -->
    <div v-if="searchVisible" class="search-modal" @click.self="closeSearch">
      <div class="search-container">
        <!-- 搜索框 -->
        <div class="search-header">
          <i class="fas fa-search header-icon"></i>
          <input
            ref="searchInput"
            v-model="keyword"
            type="text"
            class="search-input"
            placeholder="搜索功能、应用、文档..."
            @input="handleSearch"
            @keydown.esc="closeSearch"
          >
          <button v-if="keyword" class="clear-btn" @click="clearSearch">
            <i class="fas fa-times"></i>
          </button>
          <button class="close-btn" @click="closeSearch">
            <span>ESC</span>
          </button>
        </div>
        
        <!-- 搜索分类切换 -->
        <div class="search-categories">
          <button
            v-for="category in categories"
            :key="category.value"
            class="category-btn"
            :class="{ active: activeCategory === category.value }"
            @click="setCategory(category.value)"
          >
            {{ category.label }}
            <span v-if="resultCount[category.value]" class="category-count">
              {{ resultCount[category.value] }}
            </span>
          </button>
        </div>
        
        <!-- 搜索结果区域 -->
        <div class="search-results" ref="resultsContainer">
          <!-- 结果为空 -->
          <div v-if="filteredResults.length === 0 && keyword" class="empty-results">
            <i class="fas fa-search empty-icon"></i>
            <p class="empty-text">未找到与"{{ keyword }}"相关的{{ getCategoryName() }}</p>
          </div>
          
          <!-- 搜索前提示 -->
          <div v-if="!keyword && !isSearching" class="search-hint">
            <p>输入关键词开始搜索</p>
            <div class="hint-tips">
              <div class="tip-item">
                <span class="key-shortcut">Tab</span>
                <span>在结果间导航</span>
              </div>
              <div class="tip-item">
                <span class="key-shortcut">↑↓</span>
                <span>选择结果</span>
              </div>
              <div class="tip-item">
                <span class="key-shortcut">Enter</span>
                <span>打开选中项</span>
              </div>
            </div>
          </div>
          
          <!-- 搜索结果 -->
          <div v-else-if="filteredResults.length > 0" class="result-list">
            <div 
              v-for="(result, index) in filteredResults" 
              :key="result.id"
              class="result-item"
              :class="{ active: activeIndex === index }"
              @click="selectResult(result)"
              @mouseenter="activeIndex = index"
            >
              <div class="result-icon" :style="{ backgroundColor: result.iconBg || '#1890ff' }">
                <i :class="['fas', result.icon]"></i>
              </div>
              
              <div class="result-content">
                <div class="result-title">
                  <!-- 高亮匹配的关键词 -->
                  <span v-html="highlightKeyword(result.title)"></span>
                </div>
                <div class="result-path">{{ result.category }} / {{ result.subCategory }}</div>
              </div>
              
              <div class="result-shortcut">
                <span v-if="index < 9" class="key-shortcut small">{{ index + 1 }}</span>
              </div>
            </div>
          </div>
          
          <!-- 搜索中 -->
          <div v-else-if="isSearching" class="searching-state">
            <div class="searching-spinner"></div>
            <p>搜索中...</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'GlobalSearch',
  data() {
    return {
      searchVisible: false,
      keyword: '',
      isSearching: false,
      activeIndex: 0,
      activeCategory: 'all',
      categories: [
        { label: '全部', value: 'all' },
        { label: '功能', value: 'function' },
        { label: '应用', value: 'app' },
        { label: '文档', value: 'document' },
        { label: '流程', value: 'workflow' },
      ],
      allResults: [],
      searchTimeout: null
    }
  },
  computed: {
    // 根据分类筛选结果
    filteredResults() {
      if (this.activeCategory === 'all') {
        return this.allResults
      }
      return this.allResults.filter(item => item.type === this.activeCategory)
    },
    
    // 各分类的结果数量
    resultCount() {
      const counts = { all: this.allResults.length }
      
      this.categories.forEach(category => {
        if (category.value !== 'all') {
          counts[category.value] = this.allResults.filter(
            item => item.type === category.value
          ).length
        }
      })
      
      return counts
    }
  },
  mounted() {
    // 添加全局快捷键
    window.addEventListener('keydown', this.handleKeydown)
  },
  beforeUnmount() {
    window.removeEventListener('keydown', this.handleKeydown)
  },
  methods: {
    // 打开搜索
    openSearch() {
      this.searchVisible = true
      this.$nextTick(() => {
        this.$refs.searchInput?.focus()
      })
    },
    
    // 关闭搜索
    closeSearch() {
      this.searchVisible = false
      this.keyword = ''
      this.allResults = []
      this.activeIndex = 0
    },
    
    // 清空搜索
    clearSearch() {
      this.keyword = ''
      this.allResults = []
      this.activeIndex = 0
      this.$refs.searchInput?.focus()
    },
    
    // 搜索处理
    handleSearch() {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout)
      }
      
      if (!this.keyword) {
        this.allResults = []
        this.isSearching = false
        return
      }
      
      this.isSearching = true
      
      // 延迟搜索，减少请求频率
      this.searchTimeout = setTimeout(() => {
        this.performSearch()
      }, 300)
    },
    
    // 执行搜索
    performSearch() {
      // 模拟API搜索
      setTimeout(() => {
        // 生成模拟结果
        this.allResults = this.getMockResults(this.keyword)
        this.isSearching = false
        this.activeIndex = 0
      }, 500)
    },
    
    // 获取模拟结果
    getMockResults(keyword) {
      if (!keyword) return []
      
      // 模拟数据库
      const allItems = [
        // 功能
        { id: 'func1', title: '报销申请', category: '财务', subCategory: '报销', type: 'function', icon: 'fa-receipt', iconBg: '#f44336', path: '/finance/expense' },
        { id: 'func2', title: '资产申请', category: '资产', subCategory: '申请', type: 'function', icon: 'fa-laptop', iconBg: '#9c27b0', path: '/asset/apply' },
        { id: 'func3', title: '物资申领', category: '物资', subCategory: '申领', type: 'function', icon: 'fa-box', iconBg: '#3f51b5', path: '/material/apply' },
        { id: 'func4', title: '出差申请', category: '财务', subCategory: '出差', type: 'function', icon: 'fa-plane', iconBg: '#00bcd4', path: '/finance/travel' },
        
        // 应用
        { id: 'app1', title: '财务管理', category: '应用', subCategory: '财务', type: 'app', icon: 'fa-wallet', iconBg: '#4caf50', path: '/finance' },
        { id: 'app2', title: '资产管理', category: '应用', subCategory: '资产', type: 'app', icon: 'fa-laptop', iconBg: '#9c27b0', path: '/asset' },
        { id: 'app3', title: '物资管理', category: '应用', subCategory: '物资', type: 'app', icon: 'fa-box', iconBg: '#3f51b5', path: '/material' },
        
        // 文档
        { id: 'doc1', title: '财务报销制度', category: '文档', subCategory: '财务制度', type: 'document', icon: 'fa-file-alt', iconBg: '#ff9800', path: '/docs/finance' },
        { id: 'doc2', title: '资产管理规范', category: '文档', subCategory: '资产制度', type: 'document', icon: 'fa-file-alt', iconBg: '#ff9800', path: '/docs/asset' },
        
        // 流程
        { id: 'flow1', title: '报销审批流程', category: '流程', subCategory: '审批流程', type: 'workflow', icon: 'fa-project-diagram', iconBg: '#795548', path: '/workflow/expense' },
        { id: 'flow2', title: '资产申请流程', category: '流程', subCategory: '申请流程', type: 'workflow', icon: 'fa-project-diagram', iconBg: '#795548', path: '/workflow/asset' }
      ]
      
      // 过滤搜索结果
      return allItems.filter(item => {
        const lowerKeyword = keyword.toLowerCase()
        return (
          item.title.toLowerCase().includes(lowerKeyword) ||
          item.category.toLowerCase().includes(lowerKeyword) ||
          item.subCategory.toLowerCase().includes(lowerKeyword)
        )
      })
    },
    
    // 设置激活的分类
    setCategory(category) {
      this.activeCategory = category
      this.activeIndex = 0
    },
    
    // 获取当前分类名称
    getCategoryName() {
      const category = this.categories.find(c => c.value === this.activeCategory)
      return category ? category.label : '结果'
    },
    
    // 高亮关键词
    highlightKeyword(text) {
      if (!this.keyword) return text
      
      const regex = new RegExp(`(${this.keyword})`, 'gi')
      return text.replace(regex, '<span class="highlight">$1</span>')
    },
    
    // 选择结果
    selectResult(result) {
      this.closeSearch()
      
      // 导航到对应路径
      if (result.path) {
        this.$router.push(result.path)
      }
      
      // 记录到最近访问
      this.addToRecentVisited(result)
    },
    
    // 添加到最近访问
    addToRecentVisited(result) {
      const recentItems = JSON.parse(localStorage.getItem('recentVisited') || '[]')
      
      // 检查是否已存在
      const existingIndex = recentItems.findIndex(item => item.id === result.id)
      
      if (existingIndex !== -1) {
        // 更新访问时间
        recentItems[existingIndex].lastVisit = Date.now()
      } else {
        // 添加新项目
        recentItems.push({
          id: result.id,
          name: result.title,
          path: result.path,
          icon: result.icon,
          iconBg: result.iconBg,
          lastVisit: Date.now(),
          favorite: false
        })
      }
      
      // 保存回本地存储
      localStorage.setItem('recentVisited', JSON.stringify(recentItems))
    },
    
    // 处理键盘操作
    handleKeydown(e) {
      // 搜索框快捷键 Ctrl+K 或 Command+K
      if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault()
        if (this.searchVisible) {
          this.closeSearch()
        } else {
          this.openSearch()
        }
        return
      }
      
      // 搜索弹窗内的键盘操作
      if (!this.searchVisible) return
      
      switch (e.key) {
        case 'ArrowDown':
          e.preventDefault()
          this.activeIndex = (this.activeIndex + 1) % this.filteredResults.length
          this.scrollToActive()
          break
          
        case 'ArrowUp':
          e.preventDefault()
          this.activeIndex = this.activeIndex > 0 
            ? this.activeIndex - 1 
            : this.filteredResults.length - 1
          this.scrollToActive()
          break
          
        case 'Enter':
          if (this.filteredResults.length > 0) {
            e.preventDefault()
            this.selectResult(this.filteredResults[this.activeIndex])
          }
          break
          
        case 'Tab':
          e.preventDefault()
          // Tab 切换结果分类
          const categoryValues = this.categories.map(c => c.value)
          const currentIndex = categoryValues.indexOf(this.activeCategory)
          const nextIndex = (currentIndex + 1) % categoryValues.length
          this.activeCategory = categoryValues[nextIndex]
          this.activeIndex = 0
          break
      }
      
      // 数字快捷键 1-9
      if (e.key >= '1' && e.key <= '9') {
        const index = parseInt(e.key) - 1
        if (index < this.filteredResults.length) {
          e.preventDefault()
          this.selectResult(this.filteredResults[index])
        }
      }
    },
    
    // 滚动到激活项
    scrollToActive() {
      this.$nextTick(() => {
        const container = this.$refs.resultsContainer
        const activeItem = container.querySelector('.result-item.active')
        
        if (container && activeItem) {
          const containerRect = container.getBoundingClientRect()
          const activeRect = activeItem.getBoundingClientRect()
          
          if (activeRect.bottom > containerRect.bottom) {
            container.scrollTop += activeRect.bottom - containerRect.bottom
          } else if (activeRect.top < containerRect.top) {
            container.scrollTop -= containerRect.top - activeRect.top
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.global-search {
  width: 100%;
}

/* 搜索触发器 */
.search-trigger {
  display: flex;
  align-items: center;
  background-color: var(--background-grey);
  border-radius: 8px;
  padding: 8px 12px;
  cursor: pointer;
}

.search-icon {
  color: var(--text-secondary);
  margin-right: 8px;
}

.search-placeholder {
  color: var(--text-secondary);
  font-size: 14px;
}

/* 搜索模态框 */
.search-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  z-index: 1000;
  padding-top: 80px;
  backdrop-filter: blur(2px);
}

.search-container {
  width: 90%;
  max-width: 600px;
  background-color: var(--background-white);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  animation: slide-down 0.2s ease-out;
}

@keyframes slide-down {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 搜索头部 */
.search-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid var(--divider);
}

.header-icon {
  color: var(--text-secondary);
  margin-right: 12px;
  font-size: 16px;
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  background: transparent;
  color: var(--text-primary);
}

.clear-btn, .close-btn {
  background: none;
  border: none;
  padding: 4px 8px;
  cursor: pointer;
  color: var(--text-secondary);
  margin-left: 8px;
  border-radius: 4px;
}

.close-btn {
  font-size: 12px;
  background-color: var(--background-grey);
  padding: 4px 6px;
}

/* 搜索分类 */
.search-categories {
  display: flex;
  border-bottom: 1px solid var(--divider);
  padding: 0 16px;
  overflow-x: auto;
  scrollbar-width: none;
}

.search-categories::-webkit-scrollbar {
  display: none;
}

.category-btn {
  background: none;
  border: none;
  padding: 12px 16px;
  font-size: 14px;
  color: var(--text-secondary);
  cursor: pointer;
  position: relative;
  white-space: nowrap;
}

.category-btn.active {
  color: var(--primary-blue);
}

.category-btn.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background-color: var(--primary-blue);
}

.category-count {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: var(--background-grey);
  color: var(--text-secondary);
  border-radius: 50%;
  width: 18px;
  height: 18px;
  font-size: 12px;
  margin-left: 4px;
}

/* 搜索结果区域 */
.search-results {
  max-height: 60vh;
  overflow-y: auto;
}

/* 搜索结果列表 */
.result-list {
  padding: 8px 0;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.result-item:hover, .result-item.active {
  background-color: var(--background-grey);
}

.result-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 12px;
  flex-shrink: 0;
}

.result-content {
  flex: 1;
  min-width: 0;
}

.result-title {
  font-size: 14px;
  margin-bottom: 4px;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.result-path {
  font-size: 12px;
  color: var(--text-secondary);
}

.result-shortcut {
  margin-left: 8px;
}

/* 空结果 */
.empty-results, .search-hint, .searching-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: var(--text-secondary);
}

.empty-icon {
  font-size: 24px;
  margin-bottom: 8px;
  opacity: 0.5;
}

.empty-text {
  font-size: 14px;
  margin: 0;
  text-align: center;
}

/* 搜索提示 */
.hint-tips {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 16px;
  margin-top: 16px;
}

.tip-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.key-shortcut {
  background-color: var(--background-grey);
  border: 1px solid var(--divider);
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 12px;
  margin-right: 6px;
}

.key-shortcut.small {
  font-size: 10px;
  padding: 1px 5px;
}

/* 搜索中状态 */
.searching-spinner {
  width: 24px;
  height: 24px;
  border: 2px solid rgba(0, 0, 0, 0.1);
  border-top-color: var(--primary-blue);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin-bottom: 8px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 高亮匹配的关键词 */
:deep(.highlight) {
  background-color: rgba(255, 213, 79, 0.4);
  font-weight: 500;
  border-radius: 2px;
}
</style> 